<?php
session_start();

// 配置信息
define('DB_NAME', 'fragments.db');
define('ADMIN_USERNAME', 'admin');
define('ADMIN_PASSWORD', 'securepassword123'); // 实际使用中应修改为强密码
define('UPLOAD_DIR', 'uploads/');
define('MAX_FILE_SIZE', 5 * 1024 * 1024); // 5MB
define('MAX_IMAGES', 9); // 最多9张图片

// 创建数据库连接
function getDB() {
    $db = new SQLite3(DB_NAME);
    if (!$db) {
        die("无法连接到数据库");
    }
    return $db;
}

// 初始化数据库
function initDB() {
    $db = getDB();
    
    // 创建碎片信息表
    $query = "CREATE TABLE IF NOT EXISTS fragments (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        title TEXT NOT NULL,
        content TEXT NOT NULL,
        category TEXT,
        images TEXT, -- 存储JSON格式的图片路径数组
        created_at DATETIME DEFAULT CURRENT_TIMESTAMP
    )";
    $db->exec($query);
    
    // 创建用户表
    $query = "CREATE TABLE IF NOT EXISTS users (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        username TEXT UNIQUE NOT NULL,
        password TEXT NOT NULL
    )";
    $db->exec($query);
    
    // 创建默认管理员账户
    $stmt = $db->prepare("INSERT OR IGNORE INTO users (username, password) VALUES (:username, :password)");
    $stmt->bindValue(':username', ADMIN_USERNAME, SQLITE3_TEXT);
    $stmt->bindValue(':password', password_hash(ADMIN_PASSWORD, PASSWORD_DEFAULT), SQLITE3_TEXT);
    $stmt->execute();
    
    // 创建上传目录
    if (!file_exists(UPLOAD_DIR)) {
        mkdir(UPLOAD_DIR, 0755, true);
    }
}

// 检查用户是否登录
function isLoggedIn() {
    return isset($_SESSION['loggedin']) && $_SESSION['loggedin'] === true;
}

// 处理文件上传
function handleFileUpload($file) {
    // 检查文件大小
    if ($file['size'] > MAX_FILE_SIZE) {
        return ['error' => '文件大小超过限制 (最大5MB)'];
    }
    
    // 检查文件类型
    $allowed_types = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
    $file_type = mime_content_type($file['tmp_name']);
    if (!in_array($file_type, $allowed_types)) {
        return ['error' => '只允许上传JPEG, PNG, GIF或WebP格式的图片'];
    }
    
    // 生成唯一文件名
    $ext = pathinfo($file['name'], PATHINFO_EXTENSION);
    $filename = uniqid('img_', true) . '.' . $ext;
    $destination = UPLOAD_DIR . $filename;
    
    // 移动文件
    if (move_uploaded_file($file['tmp_name'], $destination)) {
        return ['success' => $destination];
    }
    
    return ['error' => '文件上传失败'];
}

// 初始化数据库
initDB();

// 处理操作请求
$action = $_GET['action'] ?? 'view';
$message = '';
$error = '';

// 处理登录
if ($action === 'login' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $username = $_POST['username'] ?? '';
    $password = $_POST['password'] ?? '';
    
    $db = getDB();
    $stmt = $db->prepare("SELECT password FROM users WHERE username = :username");
    $stmt->bindValue(':username', $username, SQLITE3_TEXT);
    $result = $stmt->execute();
    $user = $result->fetchArray(SQLITE3_ASSOC);
    
    if ($user && password_verify($password, $user['password'])) {
        $_SESSION['loggedin'] = true;
        $message = '登录成功！';
        $action = 'view';
    } else {
        $error = '用户名或密码错误';
    }
}

// 处理注销
if ($action === 'logout') {
    session_destroy();
    $message = '您已成功注销';
    $action = 'view';
}

// 处理添加碎片
if ($action === 'add' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $title = $_POST['title'] ?? '';
    $content = $_POST['content'] ?? '';
    $category = $_POST['category'] ?? '';
    $image_paths = [];
    
    if (!empty($title) && !empty($content)) {
        // 处理多图片上传
        if (!empty($_FILES['images']['name'][0])) {
            $file_count = count($_FILES['images']['name']);
            
            // 限制最多上传9张图片
            if ($file_count > MAX_IMAGES) {
                $error = "最多只能上传" . MAX_IMAGES . "张图片";
            } else {
                for ($i = 0; $i < $file_count; $i++) {
                    if ($_FILES['images']['error'][$i] === UPLOAD_ERR_OK) {
                        $file = [
                            'name' => $_FILES['images']['name'][$i],
                            'type' => $_FILES['images']['type'][$i],
                            'tmp_name' => $_FILES['images']['tmp_name'][$i],
                            'error' => $_FILES['images']['error'][$i],
                            'size' => $_FILES['images']['size'][$i]
                        ];
                        
                        $uploadResult = handleFileUpload($file);
                        if (isset($uploadResult['success'])) {
                            $image_paths[] = $uploadResult['success'];
                        } else {
                            $error = $uploadResult['error'];
                            break;
                        }
                    }
                }
            }
        }
        
        if (empty($error)) {
            $db = getDB();
            $images_json = json_encode($image_paths);
            
            $stmt = $db->prepare("INSERT INTO fragments (title, content, category, images) VALUES (:title, :content, :category, :images)");
            $stmt->bindValue(':title', $title, SQLITE3_TEXT);
            $stmt->bindValue(':content', $content, SQLITE3_TEXT);
            $stmt->bindValue(':category', $category, SQLITE3_TEXT);
            $stmt->bindValue(':images', $images_json, SQLITE3_TEXT);
            
            if ($stmt->execute()) {
                $message = '碎片信息添加成功！';
                $action = 'view';
            } else {
                $error = "添加碎片信息失败";
            }
        }
    } else {
        $error = "标题和内容不能为空";
    }
}

// 处理编辑碎片
if ($action === 'edit' && $_SERVER['REQUEST_METHOD'] === 'POST' && isLoggedIn()) {
    $id = $_POST['id'] ?? 0;
    $title = $_POST['title'] ?? '';
    $content = $_POST['content'] ?? '';
    $category = $_POST['category'] ?? '';
    
    if (!empty($title) && !empty($content) && $id) {
        $db = getDB();
        
        // 获取现有图片
        $stmt = $db->prepare("SELECT images FROM fragments WHERE id = :id");
        $stmt->bindValue(':id', $id, SQLITE3_INTEGER);
        $result = $stmt->execute();
        $fragment = $result->fetchArray(SQLITE3_ASSOC);
        
        $image_paths = [];
        if ($fragment && !empty($fragment['images'])) {
            $image_paths = json_decode($fragment['images'], true);
        }
        
        // 处理删除图片
        if (!empty($_POST['delete_images'])) {
            $delete_images = $_POST['delete_images'];
            foreach ($delete_images as $index) {
                if (isset($image_paths[$index])) {
                    $path = $image_paths[$index];
                    if (file_exists($path)) {
                        unlink($path);
                    }
                    unset($image_paths[$index]);
                }
            }
            // 重新索引数组
            $image_paths = array_values($image_paths);
        }
        
        // 处理新图片上传
        if (!empty($_FILES['images']['name'][0])) {
            $file_count = count($_FILES['images']['name']);
            $available_slots = MAX_IMAGES - count($image_paths);
            
            if ($file_count > $available_slots) {
                $error = "最多只能上传{$available_slots}张图片（总共不超过" . MAX_IMAGES . "张）";
            } else {
                for ($i = 0; $i < $file_count; $i++) {
                    if ($_FILES['images']['error'][$i] === UPLOAD_ERR_OK) {
                        $file = [
                            'name' => $_FILES['images']['name'][$i],
                            'type' => $_FILES['images']['type'][$i],
                            'tmp_name' => $_FILES['images']['tmp_name'][$i],
                            'error' => $_FILES['images']['error'][$i],
                            'size' => $_FILES['images']['size'][$i]
                        ];
                        
                        $uploadResult = handleFileUpload($file);
                        if (isset($uploadResult['success'])) {
                            $image_paths[] = $uploadResult['success'];
                        } else {
                            $error = $uploadResult['error'];
                            break;
                        }
                    }
                }
            }
        }
        
        if (empty($error)) {
            $images_json = json_encode($image_paths);
            
            $stmt = $db->prepare("UPDATE fragments SET title = :title, content = :content, category = :category, images = :images WHERE id = :id");
            $stmt->bindValue(':title', $title, SQLITE3_TEXT);
            $stmt->bindValue(':content', $content, SQLITE3_TEXT);
            $stmt->bindValue(':category', $category, SQLITE3_TEXT);
            $stmt->bindValue(':images', $images_json, SQLITE3_TEXT);
            $stmt->bindValue(':id', $id, SQLITE3_INTEGER);
            
            if ($stmt->execute()) {
                $message = '碎片信息更新成功！';
                $action = 'view';
            } else {
                $error = "更新碎片信息失败";
            }
        }
    } else {
        $error = "标题和内容不能为空";
    }
}

// 处理删除碎片
if ($action === 'delete' && isLoggedIn()) {
    $id = $_GET['id'] ?? 0;
    
    if ($id) {
        $db = getDB();
        
        // 获取图片路径
        $stmt = $db->prepare("SELECT images FROM fragments WHERE id = :id");
        $stmt->bindValue(':id', $id, SQLITE3_INTEGER);
        $result = $stmt->execute();
        $fragment = $result->fetchArray(SQLITE3_ASSOC);
        
        // 删除所有图片
        if ($fragment && !empty($fragment['images'])) {
            $image_paths = json_decode($fragment['images'], true);
            foreach ($image_paths as $path) {
                if (!empty($path) && file_exists($path)) {
                    unlink($path);
                }
            }
        }
        
        // 删除记录
        $stmt = $db->prepare("DELETE FROM fragments WHERE id = :id");
        $stmt->bindValue(':id', $id, SQLITE3_INTEGER);
        
        if ($stmt->execute()) {
            $message = '碎片信息已删除！';
        } else {
            $error = "删除碎片信息失败";
        }
    }
    $action = 'view';
}

// 获取所有碎片信息
$fragments = [];
$db = getDB();
$query = "SELECT * FROM fragments ORDER BY created_at DESC";
$result = $db->query($query);
while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
    $fragments[] = $row;
}

// 获取当前编辑的碎片（如果适用）
$editFragment = null;
if ($action === 'edit' && isset($_GET['id']) && isLoggedIn()) {
    $id = $_GET['id'];
    $stmt = $db->prepare("SELECT * FROM fragments WHERE id = :id");
    $stmt->bindValue(':id', $id, SQLITE3_INTEGER);
    $result = $stmt->execute();
    $editFragment = $result->fetchArray(SQLITE3_ASSOC);
    
    if (!$editFragment) {
        $action = 'view';
        $error = '未找到指定的碎片信息';
    }
}
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>碎片信息管理系统</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css">
    <style>
        :root {
            --primary-gradient: linear-gradient(135deg, #6a11cb 0%, #2575fc 100%);
            --secondary-gradient: linear-gradient(135deg, #ff416c 0%, #ff4b2b 100%);
            --success-gradient: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
        }
        
        body {
            background-color: #f8f9fa;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            padding-bottom: 60px;
        }
        
        .header {
            background: var(--primary-gradient);
            color: white;
            padding: 2rem 0;
            margin-bottom: 2rem;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
        }
        
        .card {
            border-radius: 12px;
            box-shadow: 0 4px 8px rgba(0,0,0,0.05);
            transition: transform 0.3s, box-shadow 0.3s;
            margin-bottom: 20px;
            overflow: hidden;
            border: none;
        }
        
        .card:hover {
            transform: translateY(-5px);
            box-shadow: 0 8px 16px rgba(0,0,0,0.1);
        }
        
        .card-header {
            background-color: rgba(106, 17, 203, 0.1);
            font-weight: 600;
            border-bottom: 1px solid rgba(0,0,0,0.05);
        }
        
        .btn-primary {
            background: var(--primary-gradient);
            border: none;
        }
        
        .btn-danger {
            background: var(--secondary-gradient);
            border: none;
        }
        
        .btn-success {
            background: var(--success-gradient);
            border: none;
        }
        
        .action-buttons {
            opacity: 0;
            transition: opacity 0.3s;
        }
        
        .card:hover .action-buttons {
            opacity: 1;
        }
        
        .category-badge {
            background: var(--success-gradient);
            color: white;
        }
        
        .fragment-image {
            width: 100%;
            height: 200px;
            object-fit: cover;
            border-radius: 8px;
            margin-bottom: 15px;
            transition: transform 0.3s;
        }
        
        .fragment-image:hover {
            transform: scale(1.05);
        }
        
        .login-container {
            max-width: 400px;
            margin: 0 auto;
        }
        
        .form-container {
            max-width: 800px;
            margin: 0 auto;
        }
        
        .footer {
            position: fixed;
            bottom: 0;
            width: 100%;
            background: white;
            box-shadow: 0 -2px 10px rgba(0,0,0,0.1);
            padding: 15px 0;
        }
        
        .preview-image {
            max-width: 100%;
            max-height: 200px;
            border-radius: 8px;
            margin-top: 10px;
        }
        
        .upload-container {
            border: 2px dashed #ddd;
            border-radius: 8px;
            padding: 20px;
            text-align: center;
            background-color: #f9f9f9;
            cursor: pointer;
            transition: border-color 0.3s;
        }
        
        .upload-container:hover {
            border-color: #6a11cb;
        }
        
        .upload-icon {
            font-size: 3rem;
            color: #6a11cb;
            margin-bottom: 10px;
        }
        
        .image-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
            gap: 15px;
            margin-top: 20px;
        }
        
        .image-item {
            position: relative;
            border-radius: 8px;
            overflow: hidden;
            box-shadow: 0 3px 6px rgba(0,0,0,0.1);
        }
        
        .image-item img {
            width: 100%;
            height: 150px;
            object-fit: cover;
            display: block;
        }
        
        .image-item .delete-btn {
            position: absolute;
            top: 5px;
            right: 5px;
            background: rgba(255, 0, 0, 0.7);
            color: white;
            border: none;
            border-radius: 50%;
            width: 24px;
            height: 24px;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
        }
        
        .image-counter {
            position: absolute;
            bottom: 5px;
            left: 5px;
            background: rgba(0, 0, 0, 0.5);
            color: white;
            padding: 2px 6px;
            border-radius: 10px;
            font-size: 12px;
        }
        
        .compression-info {
            background-color: #e9f7ef;
            border-radius: 8px;
            padding: 10px;
            margin-top: 10px;
            font-size: 14px;
        }
        
        .compression-bar {
            height: 8px;
            background-color: #e0e0e0;
            border-radius: 4px;
            margin-top: 5px;
            overflow: hidden;
        }
        
        .compression-progress {
            height: 100%;
            background: var(--success-gradient);
            width: 0%;
            transition: width 0.5s;
        }
        
        .image-preview-container {
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
            margin-top: 15px;
        }
        
        .preview-item {
            position: relative;
            width: 120px;
            height: 120px;
        }
        
        .preview-item img {
            width: 100%;
            height: 100%;
            object-fit: cover;
            border-radius: 8px;
        }
        
        .preview-item .delete-preview {
            position: absolute;
            top: 5px;
            right: 5px;
            background: rgba(255, 0, 0, 0.7);
            color: white;
            border: none;
            border-radius: 50%;
            width: 20px;
            height: 20px;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            font-size: 12px;
        }
    </style>
</head>
<body>
    <div class="header text-center">
        <div class="container">
            <h1 class="display-4 fw-bold"><i class="bi bi-collection"></i> 碎片信息管理系统</h1>
            <p class="lead">收集、整理和管理您的碎片化知识</p>
        </div>
    </div>

    <div class="container">
        <!-- 消息提示 -->
        <?php if (!empty($message)): ?>
            <div class="alert alert-success alert-dismissible fade show" role="alert">
                <?php echo $message; ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
        <?php endif; ?>
        
        <?php if (!empty($error)): ?>
            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                <?php echo $error; ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
        <?php endif; ?>
        
        <!-- 登录页面 -->
        <?php if ($action === 'login'): ?>
            <div class="login-container">
                <div class="card">
                    <div class="card-header text-center">
                        <h3><i class="bi bi-shield-lock"></i> 管理员登录</h3>
                    </div>
                    <div class="card-body p-4">
                        <form method="POST" action="?action=login">
                            <div class="mb-3">
                                <label for="username" class="form-label">用户名</label>
                                <input type="text" class="form-control" id="username" name="username" required>
                            </div>
                            
                            <div class="mb-3">
                                <label for="password" class="form-label">密码</label>
                                <input type="password" class="form-control" id="password" name="password" required>
                            </div>
                            
                            <div class="d-grid mb-3">
                                <button type="submit" class="btn btn-primary btn-lg">
                                    <i class="bi bi-box-arrow-in-right"></i> 登录
                                </button>
                            </div>
                            
                            <div class="text-center">
                                <a href="?" class="text-decoration-none">
                                    <i class="bi bi-arrow-left"></i> 返回首页
                                </a>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        
        <!-- 添加/编辑表单 -->
        <?php elseif ($action === 'add' || ($action === 'edit' && $editFragment)): ?>
            <div class="form-container">
                <div class="card">
                    <div class="card-header">
                        <h3 class="mb-0">
                            <i class="bi <?php echo $action === 'add' ? 'bi-plus-circle' : 'bi-pencil'; ?>"></i>
                            <?php echo $action === 'add' ? '添加新碎片信息' : '编辑碎片信息'; ?>
                        </h3>
                    </div>
                    <div class="card-body">
                        <form method="POST" enctype="multipart/form-data" 
                            action="?action=<?php echo $action === 'add' ? 'add' : 'edit'; ?>">
                            
                            <?php if ($action === 'edit'): ?>
                                <input type="hidden" name="id" value="<?php echo $editFragment['id']; ?>">
                            <?php endif; ?>
                            
                            <div class="mb-3">
                                <label for="title" class="form-label">标题 <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="title" name="title" 
                                    value="<?php echo $editFragment['title'] ?? ''; ?>" required>
                            </div>
                            
                            <div class="mb-3">
                                <label for="category" class="form-label">分类</label>
                                <input type="text" class="form-control" id="category" name="category" 
                                    value="<?php echo $editFragment['category'] ?? ''; ?>" 
                                    placeholder="例如：技术、生活、学习等">
                            </div>
                            
                            <div class="mb-3">
                                <label for="content" class="form-label">内容 <span class="text-danger">*</span></label>
                                <textarea class="form-control" id="content" name="content" rows="5" required><?php 
                                    echo $editFragment['content'] ?? ''; 
                                ?></textarea>
                            </div>
                            
                            <div class="mb-4">
                                <label class="form-label">图片上传（最多9张）</label>
                                
                                <div class="upload-container" onclick="document.getElementById('imageInput').click()">
                                    <i class="bi bi-cloud-arrow-up upload-icon"></i>
                                    <p class="mb-2">点击或拖放文件到此处上传</p>
                                    <p class="text-muted small">支持 JPG, PNG, GIF, WebP (每张最大 5MB)</p>
                                    <input type="file" id="imageInput" name="images[]" accept="image/*" class="d-none" 
                                        multiple onchange="handleImageSelection(this)">
                                </div>
                                
                                <div class="compression-info d-none" id="compressionInfo">
                                    <div class="d-flex justify-content-between">
                                        <span>压缩进度:</span>
                                        <span id="compressionStatus">准备压缩...</span>
                                    </div>
                                    <div class="compression-bar">
                                        <div class="compression-progress" id="compressionProgress"></div>
                                    </div>
                                </div>
                                
                                <div class="image-preview-container" id="imagePreviewContainer">
                                    <?php if ($action === 'edit' && !empty($editFragment['images'])): 
                                        $images = json_decode($editFragment['images'], true);
                                        foreach ($images as $index => $image): ?>
                                            <div class="preview-item">
                                                <img src="<?php echo $image; ?>" alt="图片预览">
                                                <input type="hidden" name="existing_images[]" value="<?php echo $image; ?>">
                                                <button type="button" class="delete-preview" onclick="removeExistingImage(this, <?php echo $index; ?>)">
                                                    <i class="bi bi-x"></i>
                                                </button>
                                            </div>
                                        <?php endforeach; ?>
                                    <?php endif; ?>
                                </div>
                                
                                <input type="hidden" name="delete_images[]" id="deleteImages" value="">
                            </div>
                            
                            <div class="d-grid gap-2">
                                <button type="submit" class="btn btn-primary btn-lg">
                                    <i class="bi bi-save"></i> 
                                    <?php echo $action === 'add' ? '保存碎片信息' : '更新碎片信息'; ?>
                                </button>
                                <a href="?" class="btn btn-outline-secondary btn-lg">
                                    <i class="bi bi-arrow-left"></i> 取消
                                </a>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        
        <!-- 主页面（碎片列表） -->
        <?php else: ?>
            <div class="d-flex justify-content-between align-items-center mb-4">
                <h2><i class="bi bi-card-list"></i> 碎片信息列表</h2>
                
                <div>
                    <a href="?action=add" class="btn btn-primary me-2">
                        <i class="bi bi-plus-circle"></i> 添加新碎片
                    </a>
                    
                    <?php if (isLoggedIn()): ?>
                        <a href="?action=logout" class="btn btn-outline-danger">
                            <i class="bi bi-box-arrow-right"></i> 注销
                        </a>
                    <?php else: ?>
                        <a href="?action=login" class="btn btn-outline-primary">
                            <i class="bi bi-lock"></i> 管理员登录
                        </a>
                    <?php endif; ?>
                </div>
            </div>
            
            <div class="row mb-4">
                <div class="col-md-6">
                    <form class="d-flex">
                        <input class="form-control me-2" type="search" placeholder="搜索碎片..." aria-label="Search">
                        <button class="btn btn-outline-primary" type="submit">搜索</button>
                    </form>
                </div>
                <div class="col-md-6 text-end">
                    <div class="btn-group">
                        <button class="btn btn-outline-secondary dropdown-toggle" type="button" data-bs-toggle="dropdown">
                            <i class="bi bi-filter"></i> 分类筛选
                        </button>
                        <ul class="dropdown-menu">
                            <li><a class="dropdown-item" href="#">所有分类</a></li>
                            <li><a class="dropdown-item" href="#">技术</a></li>
                            <li><a class="dropdown-item" href="#">生活</a></li>
                            <li><a class="dropdown-item" href="#">学习</a></li>
                        </ul>
                    </div>
                </div>
            </div>
            
            <div class="row">
                <?php if (empty($fragments)): ?>
                    <div class="col-12 text-center py-5">
                        <div class="alert alert-info">
                            <h4 class="alert-heading"><i class="bi bi-info-circle"></i> 暂无碎片信息</h4>
                            <p>点击上方的"添加新碎片"按钮开始记录您的碎片信息</p>
                        </div>
                    </div>
                <?php else: ?>
                    <?php foreach ($fragments as $fragment): 
                        $images = !empty($fragment['images']) ? json_decode($fragment['images'], true) : [];
                    ?>
                        <div class="col-md-6 col-lg-4 mb-4">
                            <div class="card h-100">
                                <?php if (!empty($images)): ?>
                                    <div id="carousel-<?php echo $fragment['id']; ?>" class="carousel slide" data-bs-ride="carousel">
                                        <div class="carousel-inner">
                                            <?php foreach ($images as $index => $image): ?>
                                                <div class="carousel-item <?php echo $index === 0 ? 'active' : ''; ?>">
                                                    <img src="<?php echo $image; ?>" class="d-block w-100 fragment-image" 
                                                        alt="<?php echo htmlspecialchars($fragment['title']); ?>">
                                                </div>
                                            <?php endforeach; ?>
                                        </div>
                                        <button class="carousel-control-prev" type="button" data-bs-target="#carousel-<?php echo $fragment['id']; ?>" data-bs-slide="prev">
                                            <span class="carousel-control-prev-icon" aria-hidden="true"></span>
                                            <span class="visually-hidden">Previous</span>
                                        </button>
                                        <button class="carousel-control-next" type="button" data-bs-target="#carousel-<?php echo $fragment['id']; ?>" data-bs-slide="next">
                                            <span class="carousel-control-next-icon" aria-hidden="true"></span>
                                            <span class="visually-hidden">Next</span>
                                        </button>
                                    </div>
                                <?php endif; ?>
                                
                                <div class="card-body">
                                    <div class="d-flex justify-content-between align-items-start mb-3">
                                        <h5 class="card-title"><?php echo htmlspecialchars($fragment['title']); ?></h5>
                                        <?php if ($fragment['category']): ?>
                                            <span class="badge category-badge rounded-pill"><?php echo htmlspecialchars($fragment['category']); ?></span>
                                        <?php endif; ?>
                                    </div>
                                    
                                    <p class="card-text"><?php echo nl2br(htmlspecialchars($fragment['content'])); ?></p>
                                    
                                    <div class="text-muted small mt-3">
                                        <i class="bi bi-clock"></i> <?php echo date('Y-m-d H:i', strtotime($fragment['created_at'])); ?>
                                        <?php if (!empty($images)): ?>
                                            <span class="ms-2">
                                                <i class="bi bi-images"></i> <?php echo count($images); ?>张图片
                                            </span>
                                        <?php endif; ?>
                                    </div>
                                </div>
                                
                                <?php if (isLoggedIn()): ?>
                                    <div class="card-footer action-buttons">
                                        <div class="d-flex justify-content-end">
                                            <a href="?action=edit&id=<?php echo $fragment['id']; ?>" 
                                                class="btn btn-sm btn-outline-primary me-2">
                                                <i class="bi bi-pencil"></i> 编辑
                                            </a>
                                            <a href="?action=delete&id=<?php echo $fragment['id']; ?>" 
                                                class="btn btn-sm btn-outline-danger" 
                                                onclick="return confirm('确定要删除这条记录吗？');">
                                                <i class="bi bi-trash"></i> 删除
                                            </a>
                                        </div>
                                    </div>
                                <?php endif; ?>
                            </div>
                        </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>
        <?php endif; ?>
    </div>
    
    <footer class="footer">
        <div class="container">
            <div class="d-flex justify-content-between align-items-center">
                <p class="mb-0">碎片信息管理系统 &copy; <?php echo date('Y'); ?></p>
                <div>
                    <?php if (isLoggedIn()): ?>
                        <span class="badge bg-success">
                            <i class="bi bi-person-check"></i> 管理员已登录
                        </span>
                    <?php else: ?>
                        <span class="badge bg-secondary">
                            <i class="bi bi-person"></i> 访客模式
                        </span>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </footer>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // 图片压缩配置
        const MAX_WIDTH = 1600; // 最大宽度
        const MAX_HEIGHT = 1200; // 最大高度
        const QUALITY = 0.8; // 压缩质量 (0.8 = 80%)
        const MAX_IMAGES = 9; // 最多9张图片
        
        // 存储压缩后的图片数据
        let compressedImages = [];
        let imagesToDelete = [];
        
        // 处理图片选择
        function handleImageSelection(input) {
            const files = input.files;
            const previewContainer = document.getElementById('imagePreviewContainer');
            const compressionInfo = document.getElementById('compressionInfo');
            const compressionProgress = document.getElementById('compressionProgress');
            const compressionStatus = document.getElementById('compressionStatus');
            
            if (files.length === 0) return;
            
            // 显示压缩信息
            compressionInfo.classList.remove('d-none');
            compressionStatus.textContent = '开始压缩...';
            compressionProgress.style.width = '0%';
            
            // 重置压缩图片数组
            compressedImages = [];
            
            // 计算剩余可上传图片数量
            const existingCount = document.querySelectorAll('.preview-item').length;
            const availableSlots = MAX_IMAGES - existingCount;
            
            if (files.length > availableSlots) {
                alert(`最多只能上传${availableSlots}张图片（总共不超过${MAX_IMAGES}张）`);
                input.value = '';
                return;
            }
            
            // 处理每张图片
            let processed = 0;
            
            for (let i = 0; i < files.length; i++) {
                const file = files[i];
                
                // 检查文件类型
                if (!file.type.match('image.*')) {
                    alert('请选择图片文件');
                    continue;
                }
                
                const reader = new FileReader();
                
                reader.onload = function(e) {
                    const img = new Image();
                    img.src = e.target.result;
                    
                    img.onload = function() {
                        // 计算压缩比例
                        let width = img.width;
                        let height = img.height;
                        
                        if (width > MAX_WIDTH) {
                            height *= MAX_WIDTH / width;
                            width = MAX_WIDTH;
                        }
                        
                        if (height > MAX_HEIGHT) {
                            width *= MAX_HEIGHT / height;
                            height = MAX_HEIGHT;
                        }
                        
                        // 创建canvas进行压缩
                        const canvas = document.createElement('canvas');
                        canvas.width = width;
                        canvas.height = height;
                        
                        const ctx = canvas.getContext('2d');
                        ctx.drawImage(img, 0, 0, width, height);
                        
                        // 转换为Blob
                        canvas.toBlob(function(blob) {
                            // 创建预览
                            const previewUrl = URL.createObjectURL(blob);
                            
                            // 添加到预览容器
                            const previewItem = document.createElement('div');
                            previewItem.className = 'preview-item';
                            
                            const imgElement = document.createElement('img');
                            imgElement.src = previewUrl;
                            imgElement.alt = '图片预览';
                            
                            const deleteBtn = document.createElement('button');
                            deleteBtn.className = 'delete-preview';
                            deleteBtn.innerHTML = '<i class="bi bi-x"></i>';
                            deleteBtn.onclick = function() {
                                previewItem.remove();
                                // 从压缩数组中移除
                                const index = compressedImages.findIndex(item => item.url === previewUrl);
                                if (index !== -1) {
                                    compressedImages.splice(index, 1);
                                }
                            };
                            
                            previewItem.appendChild(imgElement);
                            previewItem.appendChild(deleteBtn);
                            previewContainer.appendChild(previewItem);
                            
                            // 存储压缩后的图片数据
                            compressedImages.push({
                                file: blob,
                                name: file.name,
                                url: previewUrl
                            });
                            
                            // 更新进度
                            processed++;
                            const progress = Math.round((processed / files.length) * 100);
                            compressionProgress.style.width = `${progress}%`;
                            compressionStatus.textContent = `压缩中: ${processed}/${files.length}`;
                            
                            if (processed === files.length) {
                                compressionStatus.textContent = '压缩完成!';
                                setTimeout(() => {
                                    compressionInfo.classList.add('d-none');
                                }, 2000);
                            }
                        }, file.type, QUALITY);
                    };
                };
                
                reader.readAsDataURL(file);
            }
        }
        
        // 移除现有图片
        function removeExistingImage(button, index) {
            const previewItem = button.parentElement;
            previewItem.remove();
            
            // 添加到删除列表
            imagesToDelete.push(index);
            document.getElementById('deleteImages').value = imagesToDelete.join(',');
        }
        
        // 拖放上传功能
        const dropArea = document.querySelector('.upload-container');
        
        ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
            dropArea.addEventListener(eventName, preventDefaults, false);
        });
        
        function preventDefaults(e) {
            e.preventDefault();
            e.stopPropagation();
        }
        
        ['dragenter', 'dragover'].forEach(eventName => {
            dropArea.addEventListener(eventName, highlight, false);
        });
        
        ['dragleave', 'drop'].forEach(eventName => {
            dropArea.addEventListener(eventName, unhighlight, false);
        });
        
        function highlight() {
            dropArea.style.borderColor = '#6a11cb';
            dropArea.style.backgroundColor = '#f0f0ff';
        }
        
        function unhighlight() {
            dropArea.style.borderColor = '#ddd';
            dropArea.style.backgroundColor = '#f9f9f9';
        }
        
        dropArea.addEventListener('drop', handleDrop, false);
        
        function handleDrop(e) {
            const dt = e.dataTransfer;
            const files = dt.files;
            document.getElementById('imageInput').files = files;
            handleImageSelection(document.getElementById('imageInput'));
        }
    </script>
</body>
</html>